package com.woniuxy.happylife.service.impl;

import com.woniuxy.happylife.dao.RbacMenuDao;
import com.woniuxy.happylife.dao.RbacRoleDao;
import com.woniuxy.happylife.entity.RbacMenu;
import com.woniuxy.happylife.entity.RbacRole;
import com.woniuxy.happylife.entity.RbacRoleMenu;
import com.woniuxy.happylife.service.RbacMenuService;
import com.woniuxy.happylife.service.RbacRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname RbacRoleServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/2/17 15:08
 * @Created by hang
 */
@Service
public class RbacMenuServiceImpl implements RbacMenuService {

    @Resource
    RbacMenuDao rbacMenuDao;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public List<RbacMenu> findByUsername(String username) {
        //从redis中获取该用户所有菜单
        List<RbacMenu> rbacMenus = (List<RbacMenu>) redisTemplate.opsForHash().get("menu" + username, "rbacMenus");
        //如果redis中未获取到，则从数据库中获取，并将数据存储到redis中
        if(rbacMenus == null){
            rbacMenus = rbacMenuDao.findByUsername(username);
            redisTemplate.opsForHash().put("menu" + username, "rbacMenus", rbacMenus);
        }
        return rbacMenus;
    }

    @Override
    public List<String> findMenuByRoleId(int roleId) {
        return rbacMenuDao.findMenuByRoleId(roleId);
    }

    @Override
    public int updateMenus(List<String> list) {
        //先删除对应roleid的menu
        rbacMenuDao.deleteMenusByRoleId(Integer.parseInt(list.get(0)));
        //得到role对应所有menu的id
        List<Integer> menuIds = rbacMenuDao.findByMenuNames(list);

        //新建批量添加的数据
        List<RbacRoleMenu> addlist = new ArrayList<>();
        for (Integer i: menuIds) {
            RbacRoleMenu rbacRoleMenu = new RbacRoleMenu();
            rbacRoleMenu.setRoleid(Integer.parseInt(list.get(0)));
            rbacRoleMenu.setMenuid(i);
            addlist.add(rbacRoleMenu);
        }
//        System.out.println(menuIds);
//        System.out.println(addlist);
        //将新建addlist数据拿去批量添加数据库
        return rbacMenuDao.addByRoleMenus(addlist);
    }
}
